use strict;
use File::Temp qw(tempfile);

sub createPDF{
	#print "entrando a createPDF\n";
	my ($fh, $filename) = tempfile(DIR=>"/tmp");
	#binmode $fh,":utf8";

	#print "$filename\n";

	my ($title,$weather,$provincia,$texto,$enlaces,$imagenes) = @_;
	my $latex='
	\documentclass[12pt,a4paper]{article}
	\usepackage[spanish]{babel}
	\usepackage[utf8]{inputenc}
	\usepackage[pdftex]{graphicx}
	\usepackage{url}
	\begin{document}
	\title{';
		$latex.=$title;
	$latex.='}
	\author{Agent System}
	\date{\today}
	\maketitle
	';

	$latex.='\begin{figure}[hb]
	\caption{default}
	\begin{center}
	\begin{tabular}{|c|c|c|c|c|}
	\hline
	Tiempo Hoy & Tiempo Mañana & Tiempo pasado & Pais & Provincia \\\
		';
	#system('cp 64x64/1.png /tmp');
	if (defined($weather)){
		$latex.='\includegraphics[height=1cm]{64x64/'.$weather->{HOY}.'.png}%
		';
		$latex.='& ';
		$latex.='\includegraphics[height=1cm]{64x64/'.$weather->{MANA}.'.png}%
		';
		$latex.='& ';
		$latex.='\includegraphics[height=1cm]{64x64/'.$weather->{PM}.'.png}%
		';
		$latex.='& España & ';
		$latex.=$provincia.'\\'.'\\';
	}else{
		$latex.="NA & NA & NA & España & $provincia \\\\";
	}
	$latex.='
		\hline
		\end{tabular}
		\end{center}
		\label{default}
		\end{figure}
	';
	############# Cambios para prevenir errores en latex ###########
	$texto =~s/km²/kilometros cuadrados/ig;
	$texto =~ s/_/\-/ig;
	$texto =~ s/\&/\\\&/ig;
	$texto =~ s/°C/grados centigrados/ig;
	###############################################################
	$latex.=$texto;
	if (defined($$enlaces[0])){
		$latex.='\par Enlaces: \par
		';
		foreach(@{$enlaces}){
			if (defined($_)){
				$latex.=' \url{'.$_.'} \par ';
			}
		}
	}
	
	if (!defined($$imagenes[0])){
		print "No imagenes\n";
	}else{
		foreach(@{$imagenes}){
			if (defined($_)){
				$latex.='\begin{figure}[ht]
				\centering';
				my $fich=$_;
				if ($_ =~ /((\w+\.)([A-Z]+))/){
					$fich = $2.lc($3);
					if (!-e $fich){
						system("ln -s $fich $1");
					}
					#print $1."\n";
					#print $fich."\n";
				}
				$latex.='\includegraphics[width=10cm]{'.$fich.'}
				\end{figure}';
			}
		}
		
	}
	
	$latex.='\end{document}';

	print $fh $latex;
	undef $fh;

	system("pdflatex -output-directory=/tmp $filename");
	system("pdflatex -output-directory=/tmp $filename");
	system("open $filename.pdf");
}
1;
